package com.sbtr.business.material.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sbtr.business.auth.service.impl.RoleServiceImpl;
import com.sbtr.business.material.entity.MaterialInfo;
import com.sbtr.business.material.mapper.MaterialInfoMapper;
import com.sbtr.business.material.service.IMaterialInfoService;
import com.sbtr.business.project.service.IProjectService;
import com.sbtr.common.PageDto;
import com.sbtr.constant.ColumnConstant;
import com.sbtr.open.material.dto.MaterialInfoDto;
import com.sbtr.open.material.dto.MaterialInfoSearchDto;
import com.sbtr.open.project.dto.ProjectDto;
import com.sbtr.overview.dto.AllCountDto;
import com.sbtr.overview.dto.MaterialSetTypeCountDto;
import com.sbtr.util.BeanCopyUtils;
import com.sbtr.util.PageDtoUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * <p>
 * 素材图片表 服务实现类
 * </p>
 *
 * @author wangwh15

 */
@Transactional
@Service
public class MaterialInfoServiceImpl extends ServiceImpl<MaterialInfoMapper, MaterialInfo>
		implements IMaterialInfoService {


	@Autowired
	private RoleServiceImpl roleService;

	@Autowired
	private IProjectService projectService;

	@Override
	public PageDto<MaterialInfoDto> search(MaterialInfoSearchDto pro) {
		IPage<MaterialInfoDto> page = new Page<>();
		page.setSize(pro.getPageSize());
		page.setCurrent(pro.getPage());
		QueryWrapper<MaterialInfoDto> wrapper = new QueryWrapper<>();
		wrapper.eq(ColumnConstant.MATERIAL_INFO_IS_AVAILABLE, 1);
		if (null != pro.getId()) {
			wrapper.like(ColumnConstant.MATERIAL_INFO_ID, pro.getId());
		}
		if (StringUtils.isNotEmpty(pro.getFileName())) {
			wrapper.like(ColumnConstant.FILE_NAME, pro.getFileName());
		}
		if (StringUtils.isNotEmpty(pro.getFileDesc())) {
			wrapper.like(ColumnConstant.FILE_DESC, pro.getFileDesc());
		}
//		if (StringUtils.isNotEmpty(pro.getVersion())) {
//			wrapper.like(ColumnConstant.VERSION, pro.getVersion());
//		}
//		if (!roleService.isAdmin(UserUtils.getFdLoginName())) {
//			wrapper.eq(ColumnConstant.CREATER, UserUtils.getFdLoginName());
//		}
		if (StringUtils.isNotEmpty(pro.getCreater()) && !roleService.isAdmin(pro.getCreater()) ) {
			wrapper.eq(ColumnConstant.MATERIAL_INFO_CREATER, pro.getCreater());
		}

		if( null != pro.getFileTypes() && !pro.getFileTypes().isEmpty()) {
			wrapper.in(ColumnConstant.FILE_TYPE, pro.getFileTypes());
		}

		if (StringUtils.isNotEmpty(pro.getFileSize())) {
			wrapper.like(ColumnConstant.FILE_SIZE, pro.getFileSize());
		}
		if (StringUtils.isNotBlank(pro.getBelonger())) {
			wrapper.and(e->{
				e.eq("p.belonger",pro.getBelonger()).or().isNull("p.belonger");
			});
		}

		if (null != pro.getCreateTimeFrom()) {
			Date createTimeTo = pro.getCreateTimeFrom(); //取时间
			Calendar calendar = new GregorianCalendar();
			calendar.setTime(createTimeTo);
			calendar.add(calendar.DATE,1); //把日期往后增加一天,整数  往后推,负数往前移动
			createTimeTo=calendar.getTime(); //这个时间就是日期往后推一天的结果
			wrapper.between(ColumnConstant.MATERIAL_INFO_CREATE_TIME, pro.getCreateTimeFrom(), createTimeTo);
		}

		wrapper.orderByDesc("mi.id");
		page = baseMapper.customPage(page, wrapper);
		PageDto<MaterialInfoDto> pageDto = PageDtoUtils.getPageDtoByIPage(page, MaterialInfoDto.class);
		return pageDto;
	}

	@Override
	public List<String> getMaterialType(){
		return baseMapper.getMaterialType();
	}

	@Override
	public AllCountDto materialCount(String creater){
		return baseMapper.materialCount(creater);
	}

	@Override
	public List<MaterialSetTypeCountDto> materialSetTypeCount(String creater){
		return baseMapper.materialSetTypeCount(creater);
	}

	@Override
	public boolean batchDeleteById(List<Long> idList) {
		for (Long id:idList) {
//			MaterialInfo materialInfo = baseMapper.selectById(id);
			// 只有创建者或者管理员有权限删除素材集
//			Assert.isTrue(project != null && StringUtils.isNotBlank(project.getStatus())
//					&& ProjectConstant.PROJECT_STATUS_UNPUBLISH.equals(project.getStatus()), "已发布项目不允许删除");
//			Assert.isTrue((project != null && project.getCreater().equalsIgnoreCase(UserUtils.getFdLoginName()))
//					|| roleService.isAdmin(UserUtils.getFdLoginName()), "权限不足");
			baseMapper.updateIsAvailableById(id);
		}
		return true;
	}


	@Override
	public MaterialInfoDto findById(Long id) {
		return BeanCopyUtils.copyProperties(getById(id), MaterialInfoDto.class);
	}

	@Override
	public boolean deleteById(Long id) {
		return removeById(id);
	}

	@Override
	public PageDto<MaterialInfoDto> search(Long materialSetId, Long currPage,Long pageSize) {

		QueryWrapper<MaterialInfo> wrapper = new QueryWrapper<>();
		wrapper.eq("material_set_id", materialSetId).eq("is_deleted", "N").orderByDesc("id");
		IPage<MaterialInfo> page = new Page<>();
		if (currPage != null) {
			page.setCurrent(currPage);
		}
		if (pageSize != null) {
			page.setSize(pageSize);
		}
		wrapper.orderByDesc("id");
		page = page(page, wrapper);
		return PageDtoUtils.getPageDtoByIPage(page, MaterialInfoDto.class);
	}

	@Override
	public MaterialInfoDto savePojectId(MaterialInfoDto dto) {
		MaterialInfo data = BeanCopyUtils.copyProperties(dto, MaterialInfo.class);

		MaterialInfo oldMaterialInfo = getById(dto.getId());
		if (oldMaterialInfo.getProjectId() == null){//素材无项目
			updateById(data);
			oldMaterialInfo.setProjectId(dto.getProjectId());
		}else {//素材已有项目
			oldMaterialInfo.setProjectId(dto.getProjectId());
			oldMaterialInfo.setId(null);
			save(oldMaterialInfo);
		}
		return BeanCopyUtils.copyProperties(oldMaterialInfo, MaterialInfoDto.class);

	}

//	@RequestMapping(value = "", method = RequestMethod.POST)
//	public MaterialInfoDto save(@RequestBody MaterialInfoDto dto) {
//		MaterialInfo data = BeanCopyUtils.copyProperties(dto, MaterialInfo.class);
//		if(dto.getId() == null) {
//			save(data);
//			dto.setId(data.getId());
//		}else {
//			MaterialInfo oldMaterialInfo = getById(dto.getId());
//			if (oldMaterialInfo.getProjectId() == null || oldMaterialInfo.getFileSize() == null){
//				updateById(data);
//				oldMaterialInfo.setProjectId(dto.getProjectId());
//			}else {
//				oldMaterialInfo.setProjectId(dto.getProjectId());
//				oldMaterialInfo.setId(null);
//				save(oldMaterialInfo);
//			}
//			return BeanCopyUtils.copyProperties(oldMaterialInfo, MaterialInfoDto.class);
//		}
//		return dto;
//	}

	@Override
	public MaterialInfoDto save(MaterialInfoDto dto) {
		MaterialInfo data = BeanCopyUtils.copyProperties(dto, MaterialInfo.class);
		if(dto.getId() == null) {
			save(data);
			dto.setId(data.getId());
		}else {
			updateById(data);
		}
		return dto;
	}

	@Override
	public boolean batchSave(List<MaterialInfoDto> dtos) {
		return saveBatch(BeanCopyUtils.copyProperties(dtos, MaterialInfo.class));
	}

	@Override
	public MaterialInfoDto findByProjectId(Long projectId) {
		ProjectDto projectDto = projectService.findById(projectId);
		QueryWrapper<MaterialInfo> wrapper = new QueryWrapper<>();
		wrapper.in("id", projectDto.getFileId());
		List<MaterialInfo> materialInfoList = list(wrapper);
		Assert.isTrue(materialInfoList !=null && materialInfoList.size() != 0,"没有找到模型项目"+projectId+"关联的数据集");
		return BeanCopyUtils.copyProperties(materialInfoList.get(0), MaterialInfoDto.class);
	}


//	@RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
//	public boolean batchDelete(@RequestBody List<Long> idList) {
//		boolean b1 = removeByIds(idList); // 删除素材字典
//		boolean b2 = calibrationSetApi.detailBatchDelete(idList);// 删除相关标定集
//		return b1 && b2;
//	}

	@Override
	public List<MaterialInfoDto> searchByIds(List<Long> idList) {
		QueryWrapper<MaterialInfo> wrapper = new QueryWrapper<>();
		wrapper.in("id", idList);
		return BeanCopyUtils.copyProperties(list(wrapper), MaterialInfoDto.class);
	}


}
